<!-- 用户管理 -->
<template>
  <div class="children_content">
    <!-- <div class="children_content_flex"> -->
      <!-- <div class="left_box">
        <div class="tree_title">
          <div class="title">部门列表</div>
          <Icon type="md-refresh" size="20" />
        </div>

        <organ-tree @selected="treeSelected" />
      </div> -->
      <div class="right_box">
        <div class="add_btns_box">
          <div class="box_left">
            <div class="title">用户管理
            </div>
          </div>
          <div class="box_right">
            <Space>
              <Button type="primary" @click="showImp = true" icon="md-cloud-upload">导入新用户</Button>
              <Button type="primary" @click="userEdit()" icon="md-add">创建新用户</Button>
            </Space>
          </div>
        </div>
        <searchGroup v-model="searchObj" :options="searchOptions" @search="searchChange"
          @getHeight="setHeight" />

        <div class="content_table">
          <TemplateTable
            ref="tableRef"
            :data="tableData"
            :columns="tableColumns"
            :loading="loading"
            :height="tableHeight"
            :page="pageIndex"
            :page-size="pageSize"
            :total="total"
            border="none"
            size="small"
            stripe
            @page-change="handlePageChange"
          >
            <template #agent="{row}">
              <Icon v-if="row.agent" type="md-checkmark" color="#0a0" />
            </template>
            
            <template #callcenter="{row}">
              <Icon v-if="row.callcenter" type="md-checkmark" color="#0a0" />
            </template>

            <template #gdpr="{row}">
              <Icon v-if="row.gdpr" type="md-checkmark" color="#0a0" />
            </template>

            <template #superuser="{row}">
              <Icon v-if="row.superuser" type="md-checkmark" color="#0a0" />
            </template>
          </TemplateTable>
        </div>
      </div>
    <!-- </div> -->
  </div>
  <edit-dialog ref="userEditRef" v-if="showAdd" @cancel="showAdd = false"
    @submit="userAddSuccess" />
  <imp-excel v-if="showImp" @cancel="showImp = false" @submit="showImp = false" />
</template>
<script setup>
import { ref, onMounted, getCurrentInstance, inject, watch, nextTick, computed } from 'vue'
import moment from 'moment'
import { Message } from 'view-ui-plus'

import { userList, userDel } from '@/api/modules/department'

import EditDialog from './components/EditDialog.vue'
import impExcel from './components/impExcel.vue'
import TemplateTable from '@/components/TemplateTable/index.vue'
// import OrganTree from './components/OrganTree.vue'

// 屏幕高度
const screenHeight = inject('screenHeight')
// 搜索组件高度
const searchHeight = ref(null)
// 表格高度
const tableHeight = ref(0)
const loading = ref(false)
// 监听 screenHeight 的变化
watch(
  screenHeight,
  newHeight => {
    if (searchHeight.value) {
      tableHeight.value = newHeight - searchHeight.value - 245
    }
  },
  { immediate: true }
)

// 是否显示新增
const showAdd = ref(false)
const showImp = ref(false)

// 当前对象
const { proxy } = getCurrentInstance()

// 搜索树
const searchTree = ref('')

// 搜索条件字段
const searchObj = ref({
  username: '',
  id: '',
  mobile: '',
  email: ''
})

// 角色列表
const roleList = ref([
  { name: '管理员', id: 1 },
  { name: '普通用户', id: 2 },
  { name: '超级管理员', id: 3 }
])

// 搜索条件配置
const searchOptions = ref([
  { type: 'input', model: 'username', placeholder: '请输入关键字', label: '用户:' },
  { type: 'input', model: 'id', placeholder: '请输入关键字', label: '用户ID:' },
  // { type: 'select', model: 'departmentId', placeholder: '请选择部门', label: '所属部门:', dataList: departmentList.value },
  { type: 'input', model: 'mobile', placeholder: '请输入关键字', label: '手机:' },
  { type: 'input', model: 'email', placeholder: '请输入关键字', label: '电子邮件:' }
  // { type: 'select', model: 'role', placeholder: '请选择角色', label: '角色:', dataList: roleList.value },
  // { type: 'daterange', model: 'date', placeholder: '请选择日期', label: '创建日期:' },
])

const pageIndex = ref(1)
const pageSize = 20
const total = ref(0)
// 表单元素对象
const tableRef = ref(null)

// 列表数据
const tableData = ref([])

// 表格列配置
const tableColumns = computed(() => [
  {
    title: '用户',
    field: 'username',
    minWidth: 120
  },
  {
    title: '姓名',
    field: 'uname',
    minWidth: 120
  },
  {
    title: '中文名',
    field: 'lastname',
    minWidth: 120
  },
  {
    title: '电子邮件',
    field: 'email',
    minWidth: 150
  },
  {
    title: '手机',
    field: 'mobile',
    minWidth: 120
  },
  {
    title: '多媒体',
    field: 'agent',
    slot: 'agent',
    minWidth: 80
  },
  {
    title: '呼叫中心',
    field: 'callcenter',
    slot: 'callcenter',
    minWidth: 80
  },
  {
    title: '离线坐席',
    field: 'gdpr',
    slot: 'gdpr',
    minWidth: 80
  },
  {
    title: '管理员',
    field: 'superuser',
    slot: 'superuser',
    minWidth: 80
  },
  {
    title: '访客数',
    field: 'maxuser',
    minWidth: 80,
    formatter: ({ row }) => {
      if(!row.agent) return '默认'
      return row.maxuser || '默认'
    }
  },
  {
    title: '登录时间',
    field: 'lastlogintime',
    width: 140,
    formatter: ({ row }) => {
      return row.lastlogintime ? moment(row.lastlogintime).format('YYYY-MM-DD hh:mm:ss') : ''
    }
  },
  {
    title: '最大客户数',
    field: 'ecmax',
    minWidth: 100
  },
  {
    title: '操作',
    type: 'action',
    width: 140,
    align: 'center',
    fixed: 'right',
    actions: [
      {
        text: '编辑',
        type: 'edit',
        onClick: row => userEdit(row.id)
      },
      {
        text: '删除',
        type: 'del',
        onClick: row => delData(row)
      }
    ]
  }
])

const handleSubmit = values => {
  // console.log('Received values:', values);
}

// 导出
const exportCsv = () => {
  tableRef.value.tableRef.exportCsv({
    filename: '用户管理列表'
  })
}

// 批量删除
const batchDel = () => {
  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否批量删除该数据?!</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      proxy.$Message.success('确认删除')
    }
  })
}

// let organId
// const treeSelected = id => {
//   organId = id
//   getUserList(true)
// }

/**
 * 单个删除
 * @param {
 *  row: 选中行数据
 *  index: 当前数据下标
 * }
 */
const delData = row => {
  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否删除该数据?!</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await userDel({
        data: {
          id: row.id
        }
      })

      Message.success('确认删除')

      getUserList()
    }
  })
}

// 获取组件高度
const setHeight = height => {
  searchHeight.value = height
  tableHeight.value = screenHeight.value - searchHeight.value - 245
}

// 处理页码变化
const handlePageChange = page => {
  pageIndex.value = page
  getUserList()
}

const getUserList = reset => {
  if (reset) {
    pageIndex.value = 1
  }

  loading.value = true

  userList({
    query: {
      p: pageIndex.value,
      ps: pageSize
    },
    data: {
      ...searchObj.value
      // organ: organId
    }
  }).then(({ data }) => {
    tableData.value = data.topicList
    total.value = data.totalElements
  }).finally(() => {
    loading.value = false
  })
}

const searchChange = () => {
  getUserList(true)
}

const userEditRef = ref(null)
const userEdit = id => {
  showAdd.value = true
  nextTick(() => {
    userEditRef.value.initDialog(id)
  })
}

const userAddSuccess = () => {
  showAdd.value = false

  getUserList()
}

onMounted(() => {
  getUserList(true)
})
</script>

<style lang="scss" scoped></style>